'''
Created on Feb 10, 2014
rewrite class/func
@author: qzhuang
'''
import json
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.core import serializers
from django.views.generic.base import View
from django.db import models as db
from django.core.serializers.json import DjangoJSONEncoder

class JsonRestHandler(View):
    """Base RequestHandler type which provides convenience methods for writing
    JSON HTTP responses.
    """
    JSON_MIMETYPE = "application/json"

    def send_error(self, code=400, message='Bad Request'):
        """Convenience method to format an HTTP error response in a standard format.
        """
        response=HttpResponseBadRequest()
        response.status_code=code
        response['ErrorMessage']=message
        return response

    def send_success(self,objs,fields=None):
        """Convenience method to format a PhotoHunt JSON HTTP response in a standard
        format.
        """
        response=HttpResponse()
        response["Content-Type"] = self.JSON_MIMETYPE
        if isinstance(objs, basestring):
            response.write(objs)
        elif isinstance(objs, list):
            if fields is not None:
                response.write(serializers.serialize("json", objs,fields))
            response.write(serializers.serialize("json", objs))
        else:
            response.write(json.dumps(objs, cls=DjangoJSONEncoder))

        return response

class Hdl_test(JsonRestHandler):
    """handler test"""
    a={"aa":"aaaa"}
    def get(self,request):
      #return self.send_success(self.a)
      return self.send_error(code=401,message='VRR')

